<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\Cabinet;
use App\Models\CabinetPoint;
use App\Models\CabinetAlarmLog;
use Dcat\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;
use App\Handlers\WeconHandler;
use Illuminate\Support\Collection;

class CabinetChildrenController extends Controller
{
    public function index(Content $content, $pid){
        $cabinets = Cabinet::find($pid);
        return $content
            ->header($cabinets['name'])
            ->description('子柜列表')
            ->body($this->grid($pid));
    } 

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($pid)
    {
        $m = Cabinet::where('pid', $pid);
        return Grid::make($m, function (Grid $grid) use ($pid) {
            $grid->column('id', 'ID')->sortable();
            
            $grid->column('name', '名称')->display(function($name) {
                $hasLog = CabinetAlarmLog::where('cabinet_id', $this->id)->where('status', CabinetAlarmLog::STATUS_NO)->first();
                if ($hasLog) {
                    return '<span style="color: red">'.$name.'</span>';
                } else {
                    return $name;
                }
                error_log("id = ".print_r($this->id,1)."\n",3,'/tmp/joker.log');
                return $name;
            });
            // $grid->column('name','名称');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->disableCreateButton();

            $parent = Cabinet::find($pid);
            $grid->header(function ($collection) use ($parent) {
                $realtimeUrl = url('admin/cabinet-realtime').'/'.$parent['project_id'].'/'.$parent['id'];
                $historyUrl = url('admin/cabinet-history').'/'.$parent['id'];
                $compareUrl = url('admin/cabinet-compare').'/'.$parent['id'];
                $customLineUrl = url('admin/cabinet-custom').'/'.$parent['project_id'].'/'.$parent['id'];
                $alarmLogUrl = url('admin/cabinet-alarm-logs').'/'.$parent['id'];
                $alarmUrl = url('admin/cabinet-alarms').'/'.$parent['id'];
                $liveTextUrl = url('admin/cabinet-live-texts').'/'.$parent['id'];
                $historyTempUrl = url('admin/cabinet-history-temp').'/'.$parent['id'];
                $historyLineTempUrl = url('admin/cabinet-history-line-temp').'/'.$parent['id'];
                return '<div style=\'padding: 10px 10px 10px 150px; font-size:18px;\'><a href="'.$realtimeUrl.'" target="_blank">实时数据</a>&nbsp;&nbsp;&nbsp;<a  href="'.$historyUrl.'" target="_blank">历史记录</a>&nbsp;&nbsp;&nbsp;<a  href="'.$compareUrl.'" target="_blank">历史曲线</a>&nbsp;&nbsp;&nbsp;<a  href="'.$customLineUrl.'" target="_blank">特性曲线</a>&nbsp;&nbsp;&nbsp;<a  href="'.$alarmUrl.'" target="_blank">报警设置</a>&nbsp;&nbsp;&nbsp;<a  href="'.$alarmLogUrl.'" target="_blank">报警记录</a>&nbsp;&nbsp;&nbsp;<a  href="'.$liveTextUrl.'" target="_blank">实况文本</a>&nbsp;&nbsp;&nbsp;<a  href="'.$historyTempUrl.'" target="_blank">历史记录-秒级(临时)</a>&nbsp;&nbsp;&nbsp;<a  href="'.$historyLineTempUrl.'" target="_blank">历史曲线-秒级(临时)</a></div>';
            });
        });
    }

    public function show($pid, $id, Content $content)
    {
        $parent = Cabinet::find($pid);
        $self = Cabinet::find($id);
        return $content
            ->translation($self['name'])
            ->title($self['name'])
            ->description($parent['name'])
            ->body($this->detail($id));
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Cabinet(), function (Show $show) {
            $show->field('id', 'ID');
            $show->field('name','名称');

            $show->relation('points', '采集点', function ($model) {
                $grid = new Grid(new CabinetPoint);
                $grid->model()->where('cabinet_id', $model->id);
                // 设置路由
                $grid->setResource('points');
                $grid->column('alias', '采集点编号')->display(function ($alias) {
                    return str_replace('a_', '', $alias);
                });
                $grid->column('name', '采集点名称');
                $grid->disableRefreshButton();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disableActions();
                // $grid->disablePerPages();
                // $grid->simplePaginate(false);
                return $grid;
            });

            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    public function edit($pid, $id, Content $content)
    {
        $parent = Cabinet::find($pid);
        $self = Cabinet::find($id);
        return $content
            ->translation($self['name'])
            ->title($self['name'])
            ->description($parent['name'])
            ->body($this->form($pid)->edit($id));
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($pid = 0)
    {
        $builder = Cabinet::with('points');
        return Form::make($builder, function (Form $form) use ($pid) {
            $form->display('id');
            $form->text('name', '名称')->required();
            $form->hidden('pid')->value($pid);
            $form->color('color', '采集点显示颜色');
            $form->display('created_at');
            $form->display('updated_at');
            $form->hasMany('points', '采集点', function (Form\NestedForm $form) {
                $form->text('alias', '采集点编号')->customFormat(function ($alias) {
                    return str_replace('a_', '', $alias);
                })->required();
                $form->text('name', '采集点名称')->required();
                $form->radio('realtime_show', '实时数据中显示')->options(['1' => '是', '0' => '否']);
                $form->radio('history_show', '历史记录中显示')->options(['1' => '是', '0' => '否']);
                $form->radio('history_line_show', '历史曲线中显示')->options(['1' => '是', '0' => '否']);
            })->useTable();

            $form->deleted(function (Form $form, $result) {
                if ($result) {
                    $data = $form->model()->toArray();
                    Cabinet::afterDeletedCabinet($data[0]['id'], $data[0]['box_id'], $data[0]['group_id']);
                }
            });

        });
    }

    public function update($pid, $id)
    {
        return $this->form()->update($id);
    }

    public function destroy($pid, $id)
    {
        return $this->form()->destroy($id);
    }
}
